package com.tanhua;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.tanhua.template.OssTemplate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@RunWith(SpringRunner.class)
@SpringBootTest
public class OSSDemo {

    @Test
    public void test1() throws FileNotFoundException {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = "http://oss-cn-beijing.aliyuncs.com";


        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI4G9XqaE9rKQc51KorXqa";
            String accessKeySecret = "0IEmomXoHVtUYCGCsDY7X7YlePoDbZ";

        // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
            String fileName="img/2021-01-06/123.jpg";
            InputStream inputStream = new FileInputStream("C:\\Users\\muzimoo\\Desktop\\图片\\12.jpg");
            PutObjectRequest putObjectRequest = new PutObjectRequest("tanhua-142",fileName, inputStream);

        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
                ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Autowired
    private OssTemplate ossTemplate;

    @Test
    public void test2() throws FileNotFoundException {

        String file="C:\\Users\\muzimoo\\Desktop\\图片\\12.jpg";
        FileInputStream fileInputStream = new FileInputStream(file);

        //要上传的图片地址和图片流
        String url = ossTemplate.upload(file, fileInputStream);
        System.out.println(url); //保存上传到oss的地址到数据库
    }

}
